<?php
/**
 * Created by PhpStorm.
 * User: Love
 * Date: 2018/8/8
 * Time: 14:08
 */

namespace App\Http\Controllers\v1;


use AipOcr;
use App\Extend\Tools;
use App\Http\Controllers\Controller;
use foo\bar;
use Illuminate\Http\Request;
use Storage;
use Symfony\Component\HttpFoundation\File\Exception\UploadException;
use zgldh\QiniuStorage\QiniuStorage;

class OtherController extends Controller
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function image(Request $request)
    {
        $allowed = ['jpg','jpeg','png','gif'];
        $file = $request->file('source');
        if ($file->isValid()){
            //获取文件扩展名
            $ext = $file->getClientOriginalExtension();
            if (!in_array($ext,$allowed))
                throw new UploadException("图片格式不正确",204);
            $disk = QiniuStorage::disk('qiniu');
            $name = Tools::getRenderTimeChar(14).'.'.$ext;
            //如果是身份证上传，调用百度身份证识别
            $returnData = [];
            if ($request->get('type','')=='card'){
                $client = new AipOcr(env('APP_ID',''),env('API_KEY',''),env('SECRET_KEY',''));
                if ($request->get('id')==1){
                    $side = 'front';
                }else{
                    $side = 'back';
                }
                //https://huapi.yyang.xin/api/v1/image?type=card&id=1
                //18339210236 18178806659
                $result = $client->idcard(file_get_contents($file->getRealPath()),$side);
//                dd($result);
                if ($result['image_status']=='normal'){
                    if ($request->get('id')==1){
                        $data = $result['words_result'];
                        $returnData['address'] = $data['住址']['words'];
                        $returnData['birthday'] = $data['出生']['words'];
                        $returnData['name'] = $data['姓名']['words'];
                        $returnData['card'] = $data['公民身份号码']['words'];
                        $returnData['gender'] = $data['性别']['words']=='男'?1:2;
                        $returnData['nation'] = $data['民族']['words'];
                    }
                    //身份证识别正常

                    if ($result['direction']>0){
                        $this->rotate($file->getClientOriginalExtension(),$file->getRealPath(),$result['direction']);
                    }
                }else {
                    switch ($result['image_status']) {
                        case 'reversed_side':
                            $message = '未摆正身份证';
                            break;
                        case 'non_idcard':
                            $message = '上传的图片中不包含身份证';
                            break;
                        case 'blurred':
                            $message = '上传的图片中不包含身份证';
                            break;
                        case 'over_exposure':
                            $message = '上传的图片中不包含身份证';
                            break;
                        case 'unknown':
                            $message = '错误，请重新上传';
                            break;
                    }
                    throw new UploadException($message, 206);
                }
            }
            $bool = $disk->put('images/image_'.$name,file_get_contents($file->getRealPath()));


            if ($bool)
                return $this->success(array_merge($returnData,['file'=>$disk->downloadUrl('images/image_'.$name)]));

            throw new UploadException("图片上传失败",205);
        }
        throw new UploadException("图片验证失败",206);
    }

    private function rotate($type,$filename,$degrees){
        if ($type=='jpg'){
            $source = imagecreatefromjpeg($filename);
        }
        if ($type=='png'){
            $source = imagecreatefrompng($filename);
        }
        if ($type=='gif'){
            $source = imagecreatefromgif($filename);
        }
        //创建图像资源，以jpeg格式为例

        //使用imagerotate()函数按指定的角度旋转
        $rotate = imagerotate($source, $degrees*-90, 0);
        //旋转后的图片保存

        if ($type=='jpg'){
            imagejpeg($rotate,$filename);
        }
        if ($type=='png'){
            imagepng($rotate,$filename);
        }
        if ($type=='gif'){
            imagegif($rotate,$filename);
        }
        imagedestroy($rotate);
    }
}